<template>
  <Modal
      v-model="addTestPaperModal.show"
      :title="addTestPaperModal.title"
      :loading="addTestPaperModal.loading"
      :mask-closable="false"
      class="question-model"
      @on-ok="saveQuestion('paperTestformValidate')"
      @on-cancel="cancelQuestion"
      ok-text="确定"
      :width="addTestPaperModal.width"
  >
      <Row class="question-model-row">
          <Col span="24" class="question-model-col">
              <div class="flex">
                  <p v-if="!autoProduce" class="mr10">
                      当前创建的题目
                      {{
                          selectQuestionList.length ||
                              paperTestformValidate.testchaRelationList.length
                      }}
                      道
                  </p>
                  <WarningTip
                      content="调整题目、分值后，请重新保存题目信息"
                      placement="right"
                  ></WarningTip>
              </div>
              <Row v-if="singleAdd" class="question-model-row">
                  <Col span="12" style="flex: 0 0 50%;
                  max-width: 50%;" class="question-model-col">
                      <Card :bordered="false" id="allQ" dis-hover>
                          <div slot="title">
                              <p>所有题目</p>
                              <div
                                  style="
                                      float: right;
                                      margin-top: -26px;
                                      display: flex;
                                      justify-content: flex-end;
                                      width: 80%;
                                  "
                              >
                                  <Select filterable
                                      v-model="queryObjectInfo.modeCode"
                                      clearable
                                      style="width: 100px"
                                      @on-change="
                                          searchObj.pageIndex = 1;
                                          queryObjectList();
                                      "
                                  >
                                      <Option :value="1">单选题</Option>
                                      <Option :value="2">多选题</Option>
                                      <Option :value="3">判断题</Option>
                                      <Option :value="4">填空题</Option>
                                  </Select>
                                  <!-- <Select filterable
                                      v-model="queryObjectInfo.typeCode"
                                      clearable
                                      style="width:100px"
                                      @on-change="
                                          searchObj.pageIndex = 1;
                                          queryObjectList();
                                      "
                                  >
                                      <Option
                                          v-for="typecode in dealAllPoint"
                                          :value="typecode.dictid"
                                          :key="typecode.dictid"
                                          :title="typecode.dictname"
                                          >{{ typecode.dictname }}</Option
                                      >
                                  </Select> -->
                                  <Cascader
                                      change-on-select
                                      :data="treeExpClassify"
                                      v-model="queryObjectInfo.typeCode"
                                      placeholder="请选择知识点"
                                      clearable
                                      @on-change="changeCascader"
                                      style="width: 200px"
                                      class="ml10"
                                  ></Cascader>
                                  <Select filterable
                                      v-model="queryObjectInfo.difficulty"
                                      clearable
                                      style="width: 100px"
                                      class="ml10"
                                      @on-change="
                                          searchObj.pageIndex = 1;
                                          queryObjectList();
                                      "
                                  >
                                      <Option value="simple">简单</Option>
                                      <Option value="medium">中等</Option>
                                      <Option value="hard">较难</Option>
                                  </Select>
                              </div>
                          </div>
                          <div class="questionList overflow" style="font-size: 13px">
                            <Input
                                v-model="queryObjectInfo.description"
                                clearable
                                style="width:180px;margin-bottom:10px;"
                                placeholder="请输入题目"
                                @on-change="searchObj.pageIndex = 1;queryObjectList();"
                            />
                              <div style="text-align: center" v-if="showQuestionList.length == 0">
                                  没有数据
                              </div>
                              <QuestionList
                                  :data="showQuestionList"
                                  :showChecked="true"
                                  :showScore="false"
                                  @on-select="selectQuestion"
                              >
                              </QuestionList>
                              <!-- <question-list
                                  :allQuestionList="showQuestionList"
                                  :showCheckBox="true"
                                  :showParse="true"
                                  @selectQuestion="selectQuestion"
                              ></question-list> -->
                              <Button
                                  class="more"
                                  type="primary"
                                  @click="loadMore"
                                  v-show="totalCount > showQuestionList.length"
                                  >加载更多...</Button
                              >
                          </div>
                      </Card>
                  </Col>
                  <Col
                      span="11"
                      id="selQ"
                      style="width: 49%; margin-left: 2%"
                      class="question-model-col"
                  >
                      <Card dis-hover style="height: 100%">
                          <div slot="title">
                              <p style="display: inline">已选题目</p>
                              <Tag color="green">{{ selectQuestionList.length }}</Tag>
                              <small style="color: red">(选择题目上限100)</small>
                          </div>
                          <!-- <question-list
                              :allQuestionList="selectQuestionList"
                              :showDels="true"
                              @removeQuestion="removeQuestion"
                          ></question-list> -->
                          <QuestionList :data="selectQuestionList" :showActions="true" :showScore="false">
                              <template slot="action" slot-scope="{ question, index }">
                                  <InputNumber
                                      v-model="question.setScore"
                                      :max="1000"
                                      :min="1"
                                      size="small"
                                      placeholder="分值"
                                      style="width: 70px"
                                      @on-change="changeScore($event, question)"
                                  />
                                  <!-- <Tooltip
                                      content="删除"
                                      placement="bottom"
                                      :width="100"
                                      @click.native="removeQuestion(question, index)"
                                  > -->
                                  <Button
                                      type="error"
                                      size="small"
                                      @click="removeQuestion(question, index)"
                                      ><Icon type="ios-trash"
                                  /></Button>
                                  <!-- </Tooltip> -->
                              </template>
                          </QuestionList>
                      </Card>
                  </Col>
              </Row>
              <Row v-if="autoProduce" style="display: block" class="question-model-row">
                  <Col span="11" style="flex: 0 0 49%;
                  max-width: 49%;" class="question-model-col overflow">
                      <Row class="configClass header_bgcolor">
                          <Col span="24"
                              >选题总数:{{ selectQuestionList.length }} / 题目上限:100</Col
                          >
                      </Row>
                      <div style="height: calc(100% - 60px); overflow: auto">
                          <div
                              style="
                                  height: 100%;
                                  width: 100%;
                                  display: flex;
                                  justify-content: center;
                                  align-items: center;
                              "
                              v-if="loadingModeCodeOption"
                          >
                              数据获取中...
                          </div>
                          <Row
                              class="configClass"
                              v-else
                              style="margin-top: 10px; text-align: center"
                              v-for="(item, index) in modeCodeOption"
                              :key="item.id"
                          >
                              <Row style="margin-top: 0px" class="flex">
                                  <Col span="4" style="text-align: center">
                                      {{ item.label }}
                                      <p>({{ item.num }})</p>
                                  </Col>
                                  <Col span="11" class="direction">
                                      <el-cascader
                                          style="width: 100%; margin-top: 0px"
                                          :options="typeCodeObj"
                                          :props="{ multiple: true }"
                                          @change="(val) => getType(val, index + 1)"
                                          clearable
                                          collapse-tags
                                          :ref="`clearValue-${index}`"
                                          popper-class="high-level"
                                      ></el-cascader>
                                  </Col>
                                  <Col span="7">
                                      <p style="margin-bottom: 8px">
                                          选题数量 ：
                                          <InputNumber
                                              v-model="
                                                  autoPro[
                                                      index === 0
                                                          ? 'sQuestionNum'
                                                          : index === 1
                                                          ? 'mQuestionNum'
                                                          : index === 2
                                                          ? 'pQuestionNum'
                                                          : 'tQuestionNum'
                                                  ]
                                              "
                                              @on-change="changeNumber($event, index + 1)"
                                              :formatter="
                                                  (value) =>
                                                      value > 100
                                                          ? (index === 0
                                                                ? questionListS
                                                                : index === 1
                                                                ? questionListM
                                                                : index === 2
                                                                ? questionListP
                                                                : questionListT
                                                            ).length > 100
                                                              ? 100
                                                              : (index === 0
                                                                    ? questionListS
                                                                    : index === 1
                                                                    ? questionListM
                                                                    : index === 2
                                                                    ? questionListP
                                                                    : questionListT
                                                                ).length
                                                          : value.toFixed(0)
                                              "
                                              :min="0"
                                              :max="
                                                  (index === 0
                                                      ? questionListS
                                                      : index === 1
                                                      ? questionListM
                                                      : index === 2
                                                      ? questionListP
                                                      : questionListT
                                                  ).length > 100
                                                      ? 100
                                                      : (index === 0
                                                            ? questionListS
                                                            : index === 1
                                                            ? questionListM
                                                            : index === 2
                                                            ? questionListP
                                                            : questionListT
                                                        ).length
                                              "
                                              size="small"
                                          ></InputNumber>
                                          <small
                                              v-if="
                                                  autoPro[
                                                      index === 0
                                                          ? 'sQuestionNum'
                                                          : index === 1
                                                          ? 'mQuestionNum'
                                                          : index === 2
                                                          ? 'pQuestionNum'
                                                          : 'tQuestionNum'
                                                  ] >
                                                      (index === 0
                                                          ? questionListS
                                                          : index === 1
                                                          ? questionListM
                                                          : index === 2
                                                          ? questionListP
                                                          : questionListT
                                                      ).length
                                              "
                                              style="color: red; display: block"
                                              >题目数量不足</small
                                          >
                                      </p>
                                      <p style="margin-bottom: 8px">
                                          单题分值 ：
                                          <InputNumber
                                              v-model="
                                                  autoPro[
                                                      index === 0
                                                          ? 'sQuestionScore'
                                                          : index === 1
                                                          ? 'mQuestionScore'
                                                          : index === 2
                                                          ? 'pQuestionScore'
                                                          : 'tQuestionScore'
                                                  ]
                                              "
                                              @on-change="autoChangeScore($event, index + 1)"
                                              :formatter="
                                                  (value) =>
                                                      value > 100
                                                          ? 100
                                                          : value < 1
                                                          ? 1
                                                          : value
                                                          ? value
                                                          : 1
                                              "
                                              :max="100"
                                              :min="1"
                                              size="small"
                                          >
                                          </InputNumber>
                                      </p>
                                      <p>
                                          分值总计：
                                          <span style="display: inline-block; width: 80px">{{
                                              autoPro[
                                                  index === 0
                                                      ? 'sQuestionNum'
                                                      : index === 1
                                                      ? 'mQuestionNum'
                                                      : index === 2
                                                      ? 'pQuestionNum'
                                                      : 'tQuestionNum'
                                              ] *
                                                  autoPro[
                                                      index === 0
                                                          ? 'sQuestionScore'
                                                          : index === 1
                                                          ? 'mQuestionScore'
                                                          : index === 2
                                                          ? 'pQuestionScore'
                                                          : 'tQuestionScore'
                                                  ]
                                          }}</span>
                                      </p>
                                  </Col>
                              </Row>
                              <Divider dashed style="margin-top: 10px" />
                          </Row>
                      </div>
                  </Col>
                  <Col span="11" style="width: 49%; margin-left: 2%" class="question-model-col">
                      <Row
                          class="configClass"
                          style="background: var(--card-body-bgcolor-1); text-align: center"
                      >
                          <Col>已选题目({{ selectQuestionList.length }})</Col>
                      </Row>
                      <div
                          style="
                              border: 1px solid var(--card-body-bgcolor-1);
                              overflow: auto;
                              padding: 10px;
                              overflow-y: auto;
                              word-break: break-all;
                              height: calc(100% - 60px);
                          "
                      >
                          <Spin size="large" fix v-if="autoPreLoading"></Spin>
                          <!-- <question-list :allQuestionList="selectQuestionList"></question-list>
                           -->
                          <QuestionList :data="selectQuestionList"></QuestionList>
                      </div>
                  </Col>
              </Row>
          </Col>
      </Row>
  </Modal>
</template>

<script>
import encryption from '@/libs/encryption.js';
import { allDirection, experType } from '@/api/dict';
import {
  queryObjectiveList,
  queryCtfList,
  queryOprateList,
  queryObjectiveAnswerList
} from '@/api/question';
import usally from '@/mixin/usally';
import { debounce } from '@/libs/utils';
import {
  saveQuestionToKnowLedge,
  queryAllKnowLedgeQuestion,
  deleteSingleKnowLedgeQuestion
} from '@/api/knowledgeCompet';
import { mapGetters } from 'vuex';
// import questionList from './questionList';
import QuestionList from '@/components/question-list';
import dictMixin from '@/mixin/dictMixin'
export default {
  name: 'questionModel',
  mixins: [usally,dictMixin],
  components: { QuestionList },
  data() {
      let September = sessionStorage.getItem('November');
      September = JSON.parse(encryption.SelfUseDecrypt(September));
      return {
          paperTestformValidate: {
              description: '',
              difficulty: '',
              isPublic: 1,
              paperName: '',
              scores: 100,
              type: '',
              creator: September.userId,
              testchaRelationList: []
          },
          autoPreLoading: false,
          addTestPaperModal: {
              show: false,
              title: '创建题目',
              loading: true,
              testPaperName: '',
              width: 600,
              type: 1 //1---创建，2---编辑，3---预览
          },
          singleAdd: false,
          showQuestionList: [],
          selectQuestionList: [], //已选择题目列表
          savedSelectQuestion: [],
          questionListS: [], //查询到的题目总数
          oprateBtn: true,
          autoProduce: false,
          showForm: true,
          autoPro: {
              sQuestionNum: 1, //收集选择题目的数字
              pQuestionNum: 1,
              mQuestionNum: 1,
              tQuestionNum: 1,
              sQuestionType: [], // 收集筛选选择的方向
              pQuestionType: [], // 收集筛选选择的方向
              mQuestionType: [], // 收集筛选选择的方向
              tQuestionType: [], // 收集筛选选择的方向
              pQuestionScore: 1,
              mQuestionScore: 1,
              sQuestionScore: 1,
              tQuestionScore: 1,
              squstionllist: [], //
              pqustionllist: [], //
              mqustionllist: [], //
              tqustionllist: [] //
          },
          questionListS: [], //单选题
          questionListM: [], //多选题
          questionListP: [], //判断题
          questionListT: [], //填空题
          totalCount: 0,
          searchObj: {
              pageIndex: 1,
              pageSize: 10
          },
          queryObjectInfo: {
              modeCode: 1,
              typeCode: [],
              difficulty: '',
              description:''
          },
          queryObj: {
              page: 1,
              rows: 2147483647
          },
          // '单选题', '多选题', '判断题', '填空题'
          modeCodeOption: [],
          direct: [],
          treeExpClassify: [],
          typeCodeObj:[],
          loadingModeCodeOption: false
      };
  },
  computed: {
      ...mapGetters('compet', ['dealAllPoint', 'passParams']),
      checkQuestionNum() {
          let sNum = this.autoPro.sQuestionNum || 0;
          let mNum = this.autoPro.mQuestionNum || 0;
          let pNum = this.autoPro.pQuestionNum || 0;
          let tNum = this.autoPro.tQuestionNum || 0;
          return sNum + mNum + pNum + tNum;
      },
    //   typeCodeObj() {
    //       let retList = [];
    //       let list = this.direct;
    //       // 遍历两次是防止父方向还不存在，就已经添加子方向了，损失了性能，确保数据填充的正确性
    //       list.forEach((item) => {
    //           // 配置父方向
    //           if (!item.parentid) {
    //               retList.push({
    //                   value: item.dictid,
    //                   label: item.dictname,
    //                   children: []
    //               });
    //           }
    //       });
    //       list.forEach((item) => {
    //           // 配置子方向
    //           if (item.parentid) {
    //               let index = retList.findIndex((subItem) => subItem.value === item.parentid);
    //               retList[index].children.push({
    //                   value: item.dictid,
    //                   label: item.dictname
    //               });
    //           }
    //       });
    //       return retList;
    //   }
  },
  watch: {
      autoProduce(newValue) {
          if (newValue) {
              this.getObjectiveList();
          }
      },
      selectQuestionList: {
          handler(val) {
              if (val && val.length >= 100) {
                  this.showQuestionList.forEach((ques) => {
                      this.$set(ques, '_disabled', true);
                  });
              } else {
                  this.showQuestionList.forEach((ques) => {
                      this.$set(ques, '_disabled', false);
                  });
              }
          },
          deep: true
      },
      showQuestionList: {
          handler(val) {
              if (this.selectQuestionList.length >= 100) {
                  val.forEach((ques) => {
                      this.$set(ques, '_disabled', true);
                  });
              } else {
                  val.forEach((ques) => {
                      this.$set(ques, '_disabled', false);
                  });
              }
          },
          deep: true
      }
      // treeDirectionData: {
      //     handler (val) {
      //         this.treeDirectionData = val
      //     }
      // }
  },
  methods: {
      cancelQuestion(index) {
          // 清空级联选择器选中的节点
          // this.modeCodeOption.forEach((item, index) => {
          // console.log('===', this.$refs[`clearValue-${index}`]);
          // this.$refs[`clearValue-${index}`].$refs.panel.clearCheckedNodes()
          // })
      },
    //   getAllPoint() {
    //       experType().then((res) => {
    //           if (res.code == 1) {
    //               let attribute = res.attribute.attribute;
    //               this.direct = attribute[0].dictEntryList;
    //             //   let treeExpClassify = {};
    //             //   attribute[0].dictEntryList.forEach((dict) => {
    //             //       if (dict.parentid && treeExpClassify[dict.parentid]) {
    //             //           //二级
    //             //           treeExpClassify[dict.parentid].children.push({
    //             //               value: dict.dictid,
    //             //               label: dict.dictname
    //             //           });
    //             //       } else if (!treeExpClassify[dict.dictid] && !dict.parentid) {
    //             //           //一级
    //             //           treeExpClassify[dict.dictid] = {
    //             //               value: dict.dictid,
    //             //               label: dict.dictname,
    //             //               children: []
    //             //           };
    //             //       }
    //             //   });
    //               this.treeExpClassify = this.getTreeData(this.direct.filter((dict) => !dict.parentid),this.direct);
    //           }
    //       });
    //   },
    //   getTreeData(rootData = [],alldata = []) {
    //         let treeDirectionData = JSON.parse(JSON.stringify(rootData));
    //         let allData = JSON.parse(JSON.stringify(alldata));
    //         function getChildren(data){
    //             data.forEach((dict) => {
    //                 let children = allData.filter((item) => item.parentid == dict.dictid);
    //                 dict.children = children;
    //                 dict.label = dict.dictname;
    //                 dict.value = dict.dictid;
    //                 if(children.length > 0){
    //                     getChildren(children);
    //                 }
    //             });
    //         }
    //         getChildren(treeDirectionData);
    //         return treeDirectionData;
    //     },
      getSelectQuestion(selectQuestionList, totalScore, autoTotal) {
          this.selectQuestionList = selectQuestionList;
          this.totalScore = totalScore;
          this.autoTotal = autoTotal;
      },
      changeScore: debounce(function(score, question) {
          //单个创建改变分数
          let selectQuestion = this.selectQuestionList.find((ques) => ques.id == question.id);
          score = score ? (score < 1 ? 1 : score > 1000 ? 1000 : score) : 1;
          if (selectQuestion) {
              this.$set(
                  selectQuestion,
                  'setScore',
                  score ? (score < 1 ? 1 : score > 1000 ? 1000 : score) : 1
              );
          }
          this.$emit('on-change', this.copySelectQuestionList, this.totalScore);
      }, 500),
      // autoChangeScore(score, type) {
      //     this.selectQuestionList.forEach((ques) => {
      //         ques.score = score;
      //     });
      // },
      autoChangeScore: debounce(function(qscore, type) {
          //一键生成改变分数
          this.hasIllegalScore = false;
          if (this.autoPro.ctfNum > 0 && this.autoPro.ctfScore == 0) {
              this.hasIllegalScore = true;
          }
          if (this.autoPro.ctfNumEnv > 0 && this.autoPro.ctfScoreEnv == 0) {
              this.hasIllegalScore = true;
          }
          if (this.autoPro.sQuestionNum > 0 && this.autoPro.sQuestionScore == 0) {
              this.hasIllegalScore = true;
          }
          if (this.autoPro.mQuestionNum > 0 && this.autoPro.mQuestionScore == 0) {
              this.hasIllegalScore = true;
          }
          if (this.autoPro.pQuestionNum > 0 && this.autoPro.pQuestionScore == 0) {
              this.hasIllegalScore = true;
          }
          if (this.autoPro.tQuestionNum > 0 && this.autoPro.tQuestionScore == 0) {
              this.hasIllegalScore = true;
          }
          let score = qscore ? (qscore > 100 ? 100 : qscore < 1 ? 1 : qscore) : 1;
          score = Math.floor(score);
          if (type == 6) {
              this.autoPro.ctfScore = score;
              this.autoPro.ctflist.forEach((ques) => {
                  this.$set(ques, 'score', this.autoPro.ctfScore);
              });
          } else if (type == 1) {
              this.autoPro.sQuestionScore = score;
              this.autoPro.squstionllist.forEach((ques) => {
                  this.$set(ques, 'score', this.autoPro.sQuestionScor);
              });
          } else if (type == 2) {
              this.autoPro.mQuestionScore = score;
              this.autoPro.mqustionllist.forEach((ques) => {
                  this.$set(ques, 'score', this.autoPro.mQuestionScore);
              });
          } else if (type == 3) {
              this.autoPro.pQuestionScore = score;
              this.autoPro.pqustionllist.forEach((ques) => {
                  this.$set(ques, 'score', this.autoPro.pQuestionScore);
              });
          } else if (type == 4) {
              this.autoPro.tQuestionScore = score;
              this.autoPro.tqustionllist.forEach((ques) => {
                  this.$set(ques, 'score', this.autoPro.tQuestionScore);
              });
          }
          this.selectQuestionList.forEach((item) => {
              if (item.modeCode === type) {
                  this.$set(item, 'score', score);
              }
          });
      }, 500),
      initModel() {
          this.addTestPaperModal = {
              show: false,
              title: '创建题目',
              loading: true,
              testPaperName: '',
              width: 1200,
              type: 1 //1---创建，2---编辑，3---预览
          };
          this.searchObj = {
              pageIndex: 1,
              pageSize: 10
          };
          this.queryObjectInfo = {
              modeCode: 1,
              typeCode: [],
              difficulty: '',
              description:''
          };
          this.delQuestionId = [];
      },
      async singleAddQuestion(status, type, stype) {
        let {treeData,data} = await this.getDictByName('newDirectionType',true); //取缓存
            this.treeExpClassify = treeData;
            this.direct = data;
            this.typeCodeObj = treeData;
            this.initModel(stype);
            this.sfChangeType(stype);
            this.addTestPaperModal.show = true;
            if (stype == 'modify') {
                this.addTestPaperModal.title = '调整题目';
            }
      },
      sfChangeType(type) {
          //是否改变题目创建方式
          //if(this.paperTestformValidate.type == 2 && type == 1){
          if (type === 'single') {
              this.singleAdd = true;
              this.autoProduce = false;
              this.selectQuestionList = [];
              this.showQuestionList.forEach((ques) => {
                  ques._checked = false;
                  ques.score = 10;
              });
              this.queryObjectList();
              // }else if(this.paperTestformValidate.type == 1 && type == 2){
          } else if (type === 'auto') {
              this.singleAdd = false;
              this.autoProduce = true;
              this.selectQuestionList = [];
              this.autoPreLoading = false; //遮罩
              this.autoPro = {
                  sQuestionNum: 0, //收集选择题目的数字
                  pQuestionNum: 0,
                  mQuestionNum: 0,
                  tQuestionNum: 0,
                  sQuestionType: [], // 收集筛选选择的方向
                  pQuestionType: [], // 收集筛选选择的方向
                  mQuestionType: [], // 收集筛选选择的方向
                  tQuestionType: [], // 收集筛选选择的方向
                  squstionllist: [], //
                  pqustionllist: [], //
                  mqustionllist: [], //
                  tqustionllist: [], //
                  pQuestionScore: 1,
                  mQuestionScore: 1,
                  sQuestionScore: 1,
                  tQuestionScore: 1
              };
              // this.queryObjectQuestionList(1);
              this.getObjectiveList();
              this.autoProduceQustion(false);
          } else if (type === 'modify') {
              this.singleAdd = true;
              this.autoProduce = false;
              this.selectQuestionList = [];
              Promise.all([this.queryAllQuestionNotPage(), this.queryObjectList()]).then(
                  (data) => {
                      this.selectQuestionList.forEach((ques) => {
                          // let item = this.showQuestionList.filter(show=>show.id===ques.questionID || show.id === ques.id)[0];
                          if (!ques.name) {
                              this.$set(ques, 'name', ques.description);
                          }
                          let item = this.showQuestionList.find(
                              (show) => show.questionID === ques.questionID
                          );
                          if (item) {
                              item._checked = true;
                          }
                      });
                  }
              );
          }
      },
      autoProduceQustion(needPre) {
          this.addTestPaperModal.width = 1200;
          this.showForm = false;
          this.autoProduce = true;
          if (needPre) {
              this.autoPreview();
          }
      },
      getObjectiveList() {
          if (this.loadingModeCodeOption) {
              // 已经在查询过程中，不再继续调用接口
              return;
          }
          this.loadingModeCodeOption = true;
          let search = {
              pageIndex: 1,
              pageSize: 0
          };
          // queryObjectiveList 这个接口，如果一次性获取全部的由前端来分，4000 条接口 也要15s页面会卡死，不如这样调用8次接口。
          Promise.all([
              queryObjectiveList(
                  {
                      modeCode: 1
                  },
                  search
              ),
              queryObjectiveList(
                  {
                      modeCode: 2
                  },
                  search
              ),
              queryObjectiveList(
                  {
                      modeCode: 3
                  },
                  search
              ),
              queryObjectiveList(
                  {
                      modeCode: 4
                  },
                  search
              )
          ]).then((res) => {
              let modeCodeOption = [];
              res.forEach((item, index) => {
                  if (item.code !== 1) {
                      this.$Message.warning(item.message);
                  } else {
                      // '单选题', '多选题', '判断题', '填空题'
                      modeCodeOption.push(
                          Object.assign(this.modeCodeFilter(index + 1), {
                              num: item.data.total
                          })
                      );
                      this.getQuestionList(index + 1, item.data.items || []);// 这个还保留是list 数据没有出来的时候，就当选题数量为0
                  }
              });
              this.loadingModeCodeOption = false;
              this.modeCodeOption = modeCodeOption;
              this.getObjectiveItem()
          });
          
      },
      // 随机获取 各类型某一页题目
      getObjectiveItem() {
        
        for(let modeCode=1;modeCode<5;modeCode++){
          let dataTotal = this.modeCodeOption[modeCode-1].num || 0
          let pageSize = dataTotal
          
          // 每页 400 / 500 / 600 / 700 / 800 /900 / 1000    
          for(let pSize=400;pSize<1100;pSize=pSize+100){
            if(dataTotal % pSize > 400){ // 保证最后一页大于 400条 ，不大于就取全部的数据
              pageSize = pSize
              break
            }
          }
          
          let pageNum = Math.ceil(dataTotal / pageSize) || 1 // 总共页数
          let pageIndex = Math.floor(Math.random() * pageNum) + 1; // 随机某页
          let search = {
            pageIndex: pageIndex,
            pageSize: pageSize
          };
          
          queryObjectiveList(
              {
                modeCode: modeCode
              },
              search
          ).then(res=>{
            this.getQuestionList(modeCode, res.data.items || []);
          })
        }
      },
      queryQuestionList(type) {
          //根据类型查询题目列表
          this.queryCtfInfo = {
              page: 1,
              rows: 10,
              category: '',
              isNeedEnv: '0',
              isNeedSubmitFlag: '1'
          };
          this.queryObjectInfo = {
              page: 1,
              rows: 10,
              modeCode: '',
              typeCode: [],
              difficulty: '',
              description:''
          };
          this.showQuestionList = [];
          if (type == 'object') {
              //查询客观题
              this.queryObjectList();
          } else {
              this.queryCtfList();
          }
      },
      autoPreviewOld(type) {
          //自动生成题目
          this.autoPreLoading = true;
          this.autoPreIndex = 0;
          if (this.autoPro.sQuestionNum > 100) {
              this.autoPro.sQuestionNum = 100;
          }
          if (type == 1 || !type) {
              if (this.questionListS.length > this.autoPro.sQuestionNum) {
                  this.autoPro.squstionllist = this.ramdomArr(
                      this.questionListS.length,
                      this.autoPro.sQuestionNum
                  ).map((index) => {
                      return this.questionListS.slice(index, index + 1)[0];
                  });
              } else if (this.questionListS.length <= this.autoPro.sQuestionNum) {
                  this.autoPro.squstionllist = this.questionListS;
              }
              if (this.autoPro.squstionllist.length == 0) {
                  this.autoPreLoading = false;
              }
              this.autoPro.squstionllist.forEach((ques) => {
                  this.$set(ques, 'type', 'object');
                  this.queryObjectiveAnswerList(ques).then(() => {
                      this.autoPreIndex++;
                      if (type == 1 && this.autoPreIndex == this.autoPro.squstionllist.length) {
                          this.autoPreLoading = false;
                      }
                  });
              });
          }
          this.selectQuestionList = [...this.autoPro.squstionllist];
          this.selectQuestionList.forEach((ques) => {
              console.log(this.autoPro.sQuestionScore);
              this.$set(ques, 'score', this.autoPro.sQuestionScore);
          });
      },
      autoPreview() {
          //自动生成题目
          if (this.checkQuestionNum > 100) {
              this.$Message.warning('已达题目添加上限100,请修改选题数量');
              this.autoPreLoading = false;
              return;
          }
          if (this.checkQuestionNum === 0) {
              // 没有选择题目，不需要自动生成
              this.selectQuestionList = [];
              return;
          }
          this.autoPreLoading = true;
          this.autoPreIndex = 0;
          for (let i = 1; i <= 4; i++) {
              this.randomCheckQuetsion(i);
          }
          let list = [
              ...this.autoPro.squstionllist,
              ...this.autoPro.mqustionllist,
              ...this.autoPro.pqustionllist,
              ...this.autoPro.tqustionllist
          ];
          list.forEach((item) => {
              item.name = item.description;
          });
          console.log('🚀 ~ file: questionModel.vue:863 ~ autoPreview ~ list', list);
          this.selectQuestionList = this.shuffle(list);
          this.autoPreLoading = false;
      },
      // 将数组顺序打乱
      shuffle(arr) {
          var length = arr.length,
              randomIndex,
              temp;
          while (length) {
              randomIndex = Math.floor(Math.random() * length--);
              temp = arr[randomIndex];
              arr[randomIndex] = arr[length];
              arr[length] = temp;
          }
          return arr;
      },
      // 随机选中题目
      randomCheckQuetsion(type) {
          let list = '';
          let questionNum = 0;
          let listKey = '';
          let score = 0;
          switch (type) {
              case 1:
                  list = this.questionListS;
                  questionNum = this.autoPro.sQuestionNum;
                  listKey = 'squstionllist';
                  score = this.autoPro.sQuestionScore;
                  break;
              case 2:
                  list = this.questionListM;
                  questionNum = this.autoPro.mQuestionNum;
                  listKey = 'mqustionllist';
                  score = this.autoPro.mQuestionScore;
                  break;
              case 3:
                  list = this.questionListP;
                  questionNum = this.autoPro.pQuestionNum;
                  listKey = 'pqustionllist';
                  score = this.autoPro.pQuestionScore;
                  break;
              case 4:
                  list = this.questionListT;
                  questionNum = this.autoPro.tQuestionNum;
                  listKey = 'tqustionllist';
                  score = this.autoPro.tQuestionScore;
                  break;
          }
          if (list.length > questionNum) {
              this.autoPro[listKey] = this.ramdomArr(list.length, questionNum).map((index) => {
                  return list.slice(index, index + 1)[0];
              });
          } else if (list.length <= questionNum) {
              this.autoPro[listKey] = list;
          } else if (list.length === 0) {
              this.autoPro[listKey] = [];
          }
          this.autoPro[listKey].forEach((ques) => {
              this.$set(ques, 'type', 'object');
              this.$set(ques, 'score', score);
              this.queryObjectiveAnswerList(ques).then(() => {
                  this.autoPreIndex++;
                  if (this.autoPreIndex == this.checkQuestionNum) {
                      this.autoPreLoading = false;
                  }
              });
          });
      },
      //随机数函数
      ramdomArr(range, num) {
          let arr = [];
          if (range < num) {
              for (let j = 0; j < range; j++) {
                  arr.push(j);
              }
          } else {
              for (let i = 0; i < num; i++) {
                  let num = parseInt(Math.random() * range);
                  while (arr.includes(num)) {
                      num = parseInt(Math.random() * range);
                  }
                  arr.push(num);
              }
          }
          return arr;
      },

      getType(list, type) {
          this.queryObjectQuestionList(type, list);
      },
      queryObjectQuestionList(type, list) {
          console.log('🚀type, list', type, list);
          //查询客观题列表-不分页
          let obj = {};
          if (Array.isArray(list) && list.length) {
              list = list.map((item) => item[item.length - 1]); // 只取最后一只值
              obj.typeCode = list.join(',');
          }
          obj.modeCode = type;
          let search = {
              pageIndex: 1,
              pageSize: 2147483647
          };
          queryObjectiveList(obj, search).then(({ code, message, data }) => {
              if (code === 1) {
                  data.items.forEach((item) => {
                      //新接口返回数据id为原来的questionID
                      item.questionID = item.id;
                      item.name = item.description;
                  });
                  // this.questionListS = data.items || [];
                  // if (this.addTestPaperModal.show) {
                  //     this.autoPreview(val);
                  // }
                  this.modeCodeOption[type - 1].num = data.total;
                  let key =
                      type === 1
                          ? 'sQuestionNum'
                          : type === 2
                          ? 'mQuestionNum'
                          : type === 3
                          ? 'pQuestionNum'
                          : 'tQuestionNum';
                  if (data.total < this.autoPro[key]) {
                      this.$set(this.autoPro, key, data.total);
                  }
                  this.getQuestionList(type, data.items || []);
                  this.autoPreview();
              } else {
                  this.$Message.warning(message);
              }
          });
      },
      getQuestionList(type, list) {
          switch (type) {
              case 1:
                  this.questionListS = list.map((item) => {
                      item.questionID = item.id;
                      return item;
                  });
                  break;
              case 2:
                  this.questionListM = list.map((item) => {
                      item.questionID = item.id;
                      return item;
                  });
                  break;
              case 3:
                  this.questionListP = list.map((item) => {
                      item.questionID = item.id;
                      return item;
                  });
                  break;
              case 4:
                  this.questionListT = list.map((item) => {
                      item.questionID = item.id;
                      return item;
                  });
                  break;
          }
      },
      modeCodeFilter(num) {
          switch (num) {
              case 1:
                  return { id: 'single', label: '单选题' };
              case 2:
                  return { id: 'multiple', label: '多选题' };
              case 3:
                  return { id: 'judge', label: '判断题' };
              case 4:
                  return { id: 'fill', label: '填空题' };
              default:
                  return {};
          }
      },

      saveQuestion() {
          //let contestId = this.$route.query.id;
          let contestId = this.passParams.id;
          // let questionIds = this.selectQuestionList.map(question => question.questionID || question.id);
          let questions = this.selectQuestionList.map((question) => {
              return {
                  questionId: question.questionID,
                  score: this.autoProduce ? question.score : question.setScore //手动设置分数的重新定义字段
              };
          });
          let passObj = { sceneId: contestId, questionList: questions };
          // if(this.delQuestionId.length>0){
          //   deleteSingleKnowLedgeQuestion({contestId,questionIds:this.delQuestionId}).then(data=>{
          //     if(data.code===1){
          //       this.saveQuestions(passObj)
          //     }else{
          //       this.$Message.error(data.message)
          //     }
          //   })
          // }else{
          //   this.saveQuestions(passObj)
          // }
          this.saveQuestions(passObj);
      },
      saveQuestions(passObj) {
          saveQuestionToKnowLedge(passObj).then((data) => {
              if (data.code === 1) {
                  this.$Message.info('保存题目成功!');
                  this.addTestPaperModal.show = false;
                  this.$emit('queryList');
              } else {
                  this.$Message.error(data.message);
                  this.addTestPaperModal.loading = false;
                  setTimeout(() => {
                      this.addTestPaperModal.loading = true;
                  });
              }
          });
      },
      loadMore() {
          this.searchObj.pageIndex++;
          this.queryObjectList();
      },
      changeNumber(num, type) {
          if (this.checkQuestionNum > 100) {
              this.autoPro.sQuestionNum = 100;
              if (this.selectQuestionList.length >= 100) {
                  this.$Message.warning('题目添加数量已达上限100！');
                  return;
              }
          }
          if (this.checkQuestionNum < 1) {
              this.autoPro.sQuestionNum = 1;
              if (this.selectQuestionList.length >= 1) {
                  this.$Message.warning('题目添加数量不得少于1！');
              }
          }
          if (type == 1) {
              this.autoPro.sQuestionNum = num ? parseInt(num.toFixed(0)) : 0;
          } else if (type == 2) {
              this.autoPro.mQuestionNum = num ? parseInt(num.toFixed(0)) : 0;
          } else if (type == 3) {
              this.autoPro.pQuestionNum = num ? parseInt(num.toFixed(0)) : 0;
          } else if (type == 4) {
              this.autoPro.tQuestionNum = num ? parseInt(num.toFixed(0)) : 0;
          }
          if (
              (this.autoPro.tQuestionScore / this.autoPro.tQuestionNum) % 0.5 != 0 ||
              (this.autoPro.sQuestionScore / this.autoPro.sQuestionNum) % 0.5 != 0 ||
              (this.autoPro.mQuestionScore / this.autoPro.mQuestionNum) % 0.5 != 0 ||
              (this.autoPro.pQuestionScore / this.autoPro.pQuestionNum) % 0.5 != 0
          ) {
              this.hasIllegalScore = true;
          } else {
              this.hasIllegalScore = false;
          }
          this.autoPreview();
      },
      changeCascader(value) {
          this.queryObjectInfo.typeCode = value;
          this.queryObjectInfo.pageIndex = 1;
          this.queryObjectList(1);
      },
      //获取所有单选题目
      queryObjectList() {
          //查询客观题列表-分页
          if (this.searchObj.pageIndex == 1) {
              //如果查的是第一页
              this.showQuestionList = [];
          }
          let params = JSON.parse(JSON.stringify(this.queryObjectInfo));
          if (this.queryObjectInfo.typeCode) {
              params.typeCode = this.queryObjectInfo.typeCode[
                  this.queryObjectInfo.typeCode.length - 1
              ]; //.join(',')
          }
          if(!params.description ){
            delete params.description
          }
          return new Promise((resolve) => {
              queryObjectiveList(params, this.searchObj)
                  .then((data) => {
                      if (data.code == 1) {
                          data.data.items.forEach((item) => {
                              //新接口返回数据id为原来的questionID
                              item.questionID = item.id;
                          });
                          let list = data.data.items || data.data;
                          list.forEach((answer) => {
                              answer.answers &&
                                  answer.answers.forEach((subAnswer, index) => {
                                      if (
                                          subAnswer.description.indexOf('】') == 2 ||
                                          subAnswer.description.indexOf(']') == 2
                                      ) {
                                          subAnswer.description = subAnswer.description.slice(3);
                                      }
                                      if ([1, 2].includes(answer.modeCode)) {
                                          subAnswer.description = subAnswer.description;
                                      }
                                  });
                          });
                          this.objectQuestionList = list;
                          this.showQuestionList = this.showQuestionList.concat(
                              this.objectQuestionList
                          );
                          this.totalCount = data.data.total;
                          this.objectQuestionList.forEach((item) => {
                              this.$set(item, 'type', 'object');
                              if (!item.name) {
                                  this.$set(item, 'name', item.description);
                              }
                              this.$set(item, 'score', 10);
                              this.queryObjectiveAnswerList(item);
                              // if(this.selectQuestionList.filter(question => question.questionID == item.id || question.id == item.id ).length > 0){
                              if (
                                  this.selectQuestionList.filter(
                                      (question) => question.questionID == item.questionID
                                  ).length > 0
                              ) {
                                  this.$set(item, '_checked', true);
                              } else {
                                  this.$set(item, '_checked', false);
                              }
                          });
                          resolve();
                      } else {
                          this.$Message.warning(data.message);
                      }
                  })
                  .catch((error) => {});
          });
      },
      noFilter(val) {
          let num = val + 1;
          let str;
          switch (num) {
              case 1:
                  str = 'A';
                  break;
              case 2:
                  str = 'B';
                  break;
              case 3:
                  str = 'C';
                  break;
              case 4:
                  str = 'D';
                  break;
              case 5:
                  str = 'E';
                  break;
              case 6:
                  str = 'F';
                  break;
              case 7:
                  str = 'G';
                  break;
              case 8:
                  str = 'H';
                  break;
              case 9:
                  str = 'I';
                  break;
              case 10:
                  str = 'J';
                  break;
              case 11:
                  str = 'K';
                  break;
              case 12:
                  str = 'L';
                  break;
              default:
                  str = '';
                  break;
          }
          return str;
      },
      //获取单选题目下的答案
      queryObjectiveAnswerList(item) {
          //查询客观题答案
          // let id = item.chaId || item.questionID;
          return new Promise((resolve, reject) => {
              // queryObjectiveAnswerList(id).then(data=>{
              // if(data.code==1){
              // let answer = this.sortQuestionAnswer(data.data.items);
              let answer = this.sortQuestionAnswer(item.answers);
              this.$set(item, 'answers', answer);
              if (item.modeCode == 3) {
                  if (item && item.answers.length) {
                      this.$set(item, 'answers', [
                          {
                              isRight: item.answers[0].isRight == 0 ? 0 : 1,
                              answerID: '1',
                              description: '正确'
                          },
                          {
                              isRight: item.answers[0].isRight == 1 ? 0 : 1,
                              answerID: '2',
                              description: '错误'
                          }
                      ]);
                  }
              }
              resolve();
              // }
              // });
          });
      },
      //获取修改题目所有题目不分页
      queryAllQuestionNotPage() {
          return new Promise((resolve) => {
              queryAllKnowLedgeQuestion(this.passParams.id, this.queryObj)
                  .then((data) => {
                      if (data.code === 1) {
                          let ques = data.attribute.dataList;
                          ques.forEach((item) => {
                              item.setScore = item.score;
                              item.score = 10;
                              item.name = item.description;
                              if (item.keAnswerTOS) {
                                  item.answers = this.sortQuestionAnswer(item.keAnswerTOS);
                              }
                          });
                          this.selectQuestionList = ques;
                          this.savedSelectQuestion = ques.map((item) => item.id);
                          resolve();
                          //this.total = data.attribute.totalCount
                      } else {
                          this.$Message.error(data.message);
                      }
                  })
                  .catch((error) => {});
          });
      },
      //编辑单项题目
      selectQuestion(status, item) {
          //单个创建选择问题
          if (this.selectQuestionList.length >= 100) {
              this.$Message.warning('题目创建数量已达上限100！');
              return;
          }
          if (status) {
              let keAnswerTOS = [...item.answers];
              keAnswerTOS = this.sortQuestionAnswer(keAnswerTOS);
              let singleQuestion = { ...item, keAnswerTOS };
              singleQuestion.setScore = this.difficultyToScoreFilter(singleQuestion.difficulty);
              this.selectQuestionList.push(singleQuestion);
          } else {
              // let index = this.selectQuestionList.findIndex(question => question.questionID == item.id ||question.id == item.id)
              let index = this.selectQuestionList.findIndex(
                  (question) => question.questionID == item.questionID
              );
              this.selectQuestionList.splice(index, 1);
          }
          // this.$set(item, '_checked', status);
      },
      removeQuestion(ques, index) {
          //删除已选题目
          this.selectQuestionList.splice(index, 1);
          // let question = this.showQuestionList.filter(question => question.id == ques.questionID || question.id == ques.id)
          let question = this.showQuestionList.find(
              (question) => question.questionID == ques.questionID
          );
          if (question) {
              this.$set(question, '_checked', false);
          }
          if (this.savedSelectQuestion.includes(ques.id)) {
              // this.delQuestionId.push(ques.id)
              this.delQuestionId.push(ques.questionID);
          }
      },
      //难度对应分数过滤
      difficultyToScoreFilter(val) {
          let score = '';
          if (val) {
              val = val.toLowerCase();
          }
          switch (val) {
              case 'simple':
                  score = 1;
                  break;
              case 'commonly':
                  score = 2;
                  break;
              case 'medium':
                  score = 3;
                  break;
              case 'hard':
                  score = 4;
                  break;
          }
          return score;
      }
  },
  mounted() {
      
  }
};
</script>

<style scoped>
.f {
  display: flex;
}
.header_bgcolor {
  background: var(--card-body-bgcolor-1);
  text-align: center;
  height: 30px;
  line-height: 30px;
}
.question-model /deep/ .ivu-modal {
  height: calc(100% - 200px);
  min-height: 500px;
}
.question-model /deep/ .ivu-modal .ivu-modal-content {
  height: 100%;
}
.question-model /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body {
  height: calc(100% - 112px);
  padding-bottom: 20px;
}
.question-model-row,
.question-model-col {
  height: 100%;
}
.overflow {
  overflow: auto;
}
/deep/.overflow .ivu-btn-default {
  border-color: #999;
  color: #999;
}
#allQ {
  height: 100%;
}
#allQ /deep/ .ivu-card-body {
  height: calc(100% - 50px);
  overflow: auto;
}
#selQ /deep/ .ivu-card-body {
  height: calc(100% - 50px);
  overflow: auto;
}
.remove {
  display: inline-block;
  width: 15px;
  height: 15px;
  vertical-align: middle;
  background: url('../../../../assets/testPaper/remove.png') no-repeat;
}

.remove:hover {
  background: url('../../../../assets/testPaper/remove_check.png') no-repeat;
}
</style>
